package com.aloda.interceptor;

import com.aloda.constant.UserConstant;
import com.aloda.pojo.dto.UserSafetyDTO;
import com.aloda.pojo.entity.User;
import com.aloda.utils.UserHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * 登录校验拦截器，状态校验拦截器
 */
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 这里先对options请求进行处理，避免预检请求无session直接返回错误
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        // 从session中获取用户信息
        UserSafetyDTO user = (UserSafetyDTO) request.getSession().getAttribute(UserConstant.USER_SESSION_KEY);
        // 判断是否有登录状态
        if (user == null) {
            // 没有登录状态
            response.setStatus(401);
            return false;
        }
        if (UserConstant.STATUS_BANNED.equals(user.getStatus())) {
            // 强制退出
            response.setStatus(401);
            return false;
        }
        // 将用户信息放入内存
        UserHolder.saveUser(user);
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
